package com.buli.blmall.admin.common.controller;


import com.buli.blmall.admin.common.domain.WxMessage;
import com.buli.blmall.admin.common.domain.WxQrCode;
import com.buli.blmall.admin.common.response.Result;
import com.buli.blmall.admin.common.service.WeixinService;
import com.buli.blmall.admin.consts.WxConsts;
import com.buli.blmall.admin.utils.WeixinMsgUtil;
import com.buli.blmall.admin.utils.WeixinUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;


/**
 * 微信消息控制器
 * @author xiang.gao
 * @date 2025/1/14 14:10
 */
@Slf4j
@RestController
@RequestMapping("/weixin")
@AllArgsConstructor
public class WeixinController {

    private final WeixinService weixinService;

    /**
     * 微信二维码
     * @param sceneId
     * @return
     */
    @GetMapping("/qrcode")
    public Result qrCode(@RequestParam(value = "sid", required = false) String sceneId) {
        WxQrCode wxQrCode = weixinService.getWxQrCode(sceneId);
        return Result.success(wxQrCode);
    }

    /**
     * 拉取扫码登录
     * @param sceneId
     * @return
     */
    @GetMapping("/pull")
    public Result pull(@RequestParam("sid") String sceneId) {
        String openId = weixinService.pullQrCode(sceneId);
        if (StringUtils.isBlank(openId)) {
            return Result.failure("二维码已失效");
        }
        if (WxConsts.PULL_WAITING.equals(openId)) {
            return Result.waiting("请扫码关注公众号");
        }
        return Result.success(openId);
    }

    /**
     * 微信验证接口
     * @param request
     * @return
     */
    @GetMapping("/check")
    public String checkSign(HttpServletRequest request) {
        log.info("===========>checkSign");
        // 获取微信请求参数
        String signature = request.getParameter ("signature");
        String timestamp = request.getParameter ("timestamp");
        String nonce = request.getParameter ("nonce");
        String echostr = request.getParameter ("echostr");
        log.info("开始校验此次消息是否来自微信服务器，param->signature:{},\ntimestamp:{},\nnonce:{},\nechostr:{}", signature, timestamp, nonce, echostr);
        if (WeixinUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }
        return "";
    }

    /**
     * 微信公众号回调接口
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    @PostMapping("/check")
    public String weixinMsg(@RequestBody String requestBody,
                            @RequestParam("signature") String signature,
                            @RequestParam("timestamp") String timestamp,
                            @RequestParam("nonce") String nonce) {
        log.info("requestBody:{}", requestBody);
        log.info("signature:{}", signature);
        log.info("timestamp:{}", timestamp);
        log.info("nonce:{}", nonce);
        WxMessage wxMessage = WeixinMsgUtil.msgToReceiveMessage(requestBody);
        // 扫码登录
        if (WeixinMsgUtil.isScanQrCode(wxMessage)) {
            String qrCodeTicket = WeixinMsgUtil.getQrCodeTicket(wxMessage);
            String openId = wxMessage.getFromUserName();
            weixinService.scanQrCode(qrCodeTicket, openId);
            return wxMessage.getReplyTextMsg("你已成功登录！");
        }
        // 关注
        if (WeixinMsgUtil.isEventAndSubscribe(wxMessage)) {
            return wxMessage.getReplyTextMsg("欢迎关注公众号");
        }
        return wxMessage.getReplyTextMsg("收到（自动回复）");
    }

/*
    *//**
     * 配置在微信公众号后台配置的回调地址
     * @param request
     * @return
     *//*
    @GetMapping("/callback")
    public String callback (HttpServletRequest request) {
        try {
            String echostr = request.getParameter ("echostr");

            String code = request.getParameter("code");
            log.info("用户code：{}", code);
            String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WxConsts.APP_ID +
                    "&secret=" + WxConsts.APP_SECRET +
                    "&code=" + code +
                    "&grant_type=authorization_code";
            String response = HttpUtil.doGet(accessTokenUrl);
            log.info("get accessToken response:{}", response);

            JSONObject json = JSONObject.parse(response);
            String accessToken = json.getString("access_token");
            String openId = json.getString("openid");
            // 获取用户信息
            String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId;
            String userInfoResponse = HttpUtil.doGet(userInfoUrl);
            log.info("get userinfo response:{}", userInfoResponse);

            // 返回或保存用户信息
            return echostr;
        }   catch (Exception e) {
            log.error("获取accessToken失败", e);
            return "";
        }
    }*/
}
